<style lang="less" scoped>
.code-list {
  display: flex;
  justify-content: center;
  padding: 20px;
  & > li {
    text-align: center;
    margin: 0 20px;
    & > img {
      background: #fff;
      width: 160px;
      height: 160px;
      margin-bottom: 10px;
    }
  }
}
.sign-form {
  height: auto;
  padding: 20px 40px;
  background: rgba(1, 33, 72, 0.6);
  box-shadow: 0px 0px 20px 1px rgba(63, 149, 255, 1) inset;
  border-radius: 10px;
  .title {
    margin-bottom: 20px;
    font-size: 24px;
    text-align: center;
    color: #fff;
  }
  .el-form-item {
    margin-bottom: 25px !important;
  }
  .el-input {
    line-height: 40px !important;
  }
  /deep/ .el-input__inner {
    height: 40px !important;
    font-size: 15px !important;
    padding-left: 55px;
  }
  .el-form-item__content {
    position: relative;
  }
  .iconfont {
    font-size: 16px;
    margin-left: 15px;
  }
}
</style>
<template>
  <div class="page page-login">
    <div class="login-blk">
      <img class="logo" src="../assets/images/logo.png" alt />
      <el-form
        class="login-form"
        ref="form"
        :model="form"
        label-width="0px"
        v-show="sign"
      >
        <h2 class="title">登录</h2>
        <el-form-item
          prop="accountname"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.accountname" placeholder="请输入用户名">
            <i slot="prefix" class="iconfont icon-user"></i>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="accountpassword"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input
            v-model="form.accountpassword"
            type="password"
            placeholder="请输入密码"
          >
            <i slot="prefix" class="iconfont icon-lock"></i>
          </el-input>
        </el-form-item>
        <slider v-model="isLock" @change="handlerLock" v-if="sign" />

        <el-form-item class="mt-36">
          <el-button
            :disabled="loading"
            size="large"
            type="primary"
            class="full mb-0"
            @click="onSubmit"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item>
          <div class="flex fl-bw">
            <el-link type="primary" :underline="false" @click="goSign"
              >注册</el-link
            >
            <el-link type="primary" :underline="false" @click="goRetrieve"
              >忘记密码？</el-link
            >
          </div>
          <!-- <el-button size="large" type="text" class="full mt-0" @click="sign = false">注册</el-button> -->
        </el-form-item>
      </el-form>
      <el-form
        class="sign-form"
        ref="signForm"
        :model="signForm"
        label-width="0px"
        v-show="!sign"
      >
        <h2 class="title">注册</h2>
        <el-form-item>
          <el-radio-group v-model="signForm.type">
            <el-radio :label="1">运营单位</el-radio>
            <el-radio :label="2">业主单位</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="name"
          :rules="[
            { required: true, message: '请输入单位名称', trigger: 'blur' },
          ]"
        >
          <el-input v-model="signForm.name" placeholder="请输入单位名称">
            <i slot="prefix" class="iconfont icon-user"></i>
          </el-input>
        </el-form-item>

        <el-form-item
          prop="accountPassword"
          :rules="[
            { required: true, message: '请输入密码', trigger: 'change' },
            { validator: validatePass, trigger: 'change' },
          ]"
        >
          <el-input
            v-model="signForm.accountPassword"
            type="password"
            placeholder="请输入密码"
          >
            <i slot="prefix" class="iconfont icon-lock"></i>
          </el-input>
        </el-form-item>

        <el-form-item
          prop="password"
          :rules="[
            { required: true, message: '请确认密码', trigger: 'blur' },
            { validator: validatePass2, trigger: 'change' },
          ]"
        >
          <el-input
            v-model="signForm.password"
            type="password"
            placeholder="请确认密码"
          >
            <i slot="prefix" class="iconfont icon-apassword"></i>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="phone"
          :rules="[
            { required: true, message: '请输入手机号', trigger: 'change' },
            { validator: validatePhone, trigger: 'change' },
          ]"
        >
          <el-input
            v-model="signForm.phone"
            type="phone"
            placeholder="请输入手机号码"
          >
            <i slot="prefix" class="iconfont icon-phone"></i>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="code"
          :rules="[
            { required: true, message: '请输入验证码', trigger: 'change' },
          ]"
        >
          <el-input v-model="signForm.code" placeholder="请输入验证码">
            <i slot="prefix" class="iconfont icon-code"></i>
            <div
              slot="append"
              @click="getCode"
              class="pointer"
              v-if="codeTime == 0"
            >
              获取验证码
            </div>
            <div slot="append" class="pointer" v-else>
              {{ codeTime }}s后重新获取
            </div>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="signForm.invitationCode"
            placeholder="请输入邀请码"
          >
            <i slot="prefix" class="iconfont icon-invite"></i>
          </el-input>
        </el-form-item>
        <el-form-item class="mt-36">
          <el-button
            size="large"
            :disabled="loading"
            type="primary"
            class="full"
            @click="onRegister"
            >注册</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="large" class="full" @click="sign = true"
            >取消</el-button
          >
        </el-form-item>
        <div class="fl-bw">
          <div />
          <el-button type="text" :disabled="loading" @click="sign = true"
            >已有账号？立刻登录</el-button
          >
        </div>
      </el-form>
    </div>
    <div class="star"></div>
    <div class="star star1"></div>
    <div class="star star2"></div>
    <div class="star star3"></div>
    <div class="star star4"></div>
    <el-dialog
      v-if="pwdModalVisible"
      title="修改密码"
      :visible.sync="pwdModalVisible"
      width="620px"
      :close-on-click-modal="false"
      append-to-body
      :show-close="false"
    >
      <reset-pwd @success="submitSuccessAction" info />
    </el-dialog>
    <el-dialog
      v-if="unitModalVisible"
      title="完善基础信息"
      :visible.sync="unitModalVisible"
      width="620px"
      :close-on-click-modal="false"
      append-to-body
      :show-close="false"
    >
      <modifyEnterprise
        ref="newData"
        @success="submitSuccessActiont"
        @fail="adding = false"
        @submitting="adding = true"
        :unitList="unitList"
        :levelList="levelList"
        region
      ></modifyEnterprise>
      <div slot="footer">
        <el-button type="cancel" @click="unitModalVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="adding"
          @click="submitAction"
          :disabled="!$store.getters.hasEditPermission"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import utils from "@/assets/js/utils";
import { post } from "@/assets/js/request";
import ResetPwd from "../components/resetPwd.vue";
import modifyEnterprise from "@/components/census/record/RecordNew.vue";
import { mapState } from "vuex";
import Slider from "../components/slider.vue";
export default {
  name: "Login",
  data() {
    return {
      form: {
        accountname: "",
        accountpassword: "",
      },
      loading: false,
      imgBaseUrl: this.config.fileUrl + "/uploads/qrcode",
      pwdModalVisible: false,
      isLock: false,
      sign: true,
      password: "",
      signForm: {
        type: 1,
      },
      codeTime: 0,
      timer: null,
      codeShow: false,
      unitModalVisible: false,
      adding: false,
      unitList: [],
      levelList: [],
    };
  },
  components: { ResetPwd, Slider, modifyEnterprise },
  computed: {
    ...mapState(["siteInfos"]),
  },
  methods: {
    goRetrieve() {
      this.$router.push("/retrieve");
    },
    getDict(groupname, cbk) {
      this.$get("/business/business/dictList", {
        groupname: groupname,
      }).then(
        (res) => {
          cbk && cbk(res.data);
        },
        (err) => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getData() {
      this.getDict("单位性质", (data) => {
        this.unitList = data;
        this.unitObj = data.map((item) => {
          let temp = {};
          temp[item.id] = item.name;
          return temp;
        });
      });
      this.getDict("消防等级", (data) => {
        this.levelList = data;
      });
      this.unitModalVisible = true;
    },
    submitSuccessActiont(data) {
      this.$post("/systemsetup/systemsetup/updateUserHomeId", {
        userId: this.siteInfos.userId,
        businessId: data.data,
      }).then(
        (res) => {
          if (res.code == 0) {
            this.adding = false;
            this.unitModalVisible = false;
            this.$message.success("设置成功,请重新登录!");
          }
        },
        (err) => {
          this.$message.error(err.msg);
        }
      );
    },
    submitAction() {
      this.$refs.newData.submitAction();
    },
    clearTimer() {
      clearTimeout(this.timer);
      this.timer = null;
      this.codeTime = 0;
    },
    getCode() {
      if (!this.signForm.phone) {
        this.$message.error("请输入手机号!");
        return;
      }
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.codeShow = true;
        this.codeTime = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.codeTime == 0) {
            this.clearTimer();
            this.codeShow = false;
          } else {
            this.codeTime--;
          }
        }, 1000);
      }
      this.$post("/notice/notice/register", {
        phone: this.signForm.phone,
      }).then(
        (res) => {
          if (res.code == 1) {
            this.clearTimer();
            this.codeShow = false;
            this.$message.error(res.msg);
          }
        },
        (err) => {
          this.clearTimer();
          this.codeShow = false;
          this.$message.error(err.msg);
        }
      );
    },
    goSign() {
      this.sign = false;
      this.form = {};
    },
    onRegister() {
      this.$refs["signForm"].validate((valid) => {
        if (valid) {
          delete this.signForm.password;
          this.loading = true;
          this.$post("/systemsetup/systemsetup/register", this.signForm).then(
            (res) => {
              this.isLock = false;
              this.loading = false;
              if (res.code == 0) {
                this.$alert("注册成功，请使用手机号登录", "提示", {
                  confirmButtonText: "确定",
                  callback: (action) => {
                    this.sign = true;
                  },
                });
                // this.$message.success("注册成功,请返回登录");
              }
            },
            (err) => {
              this.loading = false;
              this.$message.error(err.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    validatePass2(rule, value, callback) {
      if (value !== this.signForm.accountPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },
    validatePass(rule, value, callback) {
      const reg =
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;
      if (!reg.test(value)) {
        callback(
          new Error(
            "请输入8-16位字符,可使用大写字母,小写字母,数字或符号的至少三种组合"
          )
        );
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      const reg =
        /^((13[0-9])|(14)|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    },
    handlerLock(data) {
      if (data) {
        // console.log(data);
      }
    },
    isPassword() {
      const reg = new RegExp(
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/
      );
      return reg.test(this.form.accountpassword);
    },
    onSubmit(e) {
      e.preventDefault();
      if (!this.isLock) {
        this.$message.error("请验证后登录!");
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.isLock = false;
          this.$post("/systemsetup/systemsetup/login", this.form).then(
            (res) => {
              this.loading = false;
              if (this.isPassword()) {
                this.$store.commit("setSiteInfos", res.data);
                if (res.data.homeId) {
                  this.$message.success("登录成功");
                  this.$router.replace("/IOT");
                } else {
                  this.getData();
                }
              } else {
                this.pwdModalVisible = true;
              }
            },
            (err) => {
              this.loading = false;
              this.$message.error(err.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    submitSuccessAction() {
      this.pwdModalVisible = false;
      this.form.accountpassword = "";
    },
  },
  created() {
    this.closeFullLoading();
    const loginerror = this.$route.query.loginerror;
    if (loginerror) {
      this.$message.error(loginerror);
    }
  },
  activated() {},
  mounted() {},
  beforeDestroy() {
    this.clearTimer();
  },
};
</script>
